// pages/search_news/index.js
const app = getApp()
const fetch = require('../../utils/fetch')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region_id: '150921',
    newsDatas: [],
    newDatasRecord: { "datas": [], "page": 0, "isLoaded": false },
    hasNews: false,
    search_key:"",
    defaultOptions:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.defaultOptions = options;
    this.loadNewsInfos(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },
  onClickSearch:function(e){
    var v = e.detail.value;
    this.data.search_key = v;
    this.data.newsDatas= [];
    this.data.newDatasRecord= { "datas": [], "page": 0, "isLoaded": false };
    this.loadNewsInfos(this.data.defaultOptions);
    console.log(e, "onClickSearch", this.data.search_key);
  },
  loadNewsInfos: function (options) {
    console.log(options);
    // 依据不同参数，设置不同内容
    var that = this;
    // 原数据
    var oldDatas = this.data.newDatasRecord;

    var params = { "code": this.data.region_id,'page': oldDatas.page }

    if (this.data.search_key!=""){
      params["search_key"] = this.data.search_key;
    }
    
    if("type" in options){
      params['type'] = options['type'];
    }
    if ("tags" in options) {
      params['tags'] = options['tags'];
    }
    if ("isImportant" in options) {
      params['isImportant'] = options['isImportant'];
    }
    

    console.log(options);

    fetch('yggc/commonApi/searchNews', params).then(function (result) {
      console.log(result);
      var code = result.data.code;
      if (code == 200) {

        // 原type=1的数据
        var newDatasRecord = oldDatas;
        // 追加新数据
        newDatasRecord.datas = newDatasRecord.datas.concat(result.data.data);
        console.log(result.data.data.length);
        if (result.data.data.length > 0) {
          newDatasRecord.page += 1;
        }
        newDatasRecord.isLoaded = true;
        console.log(newDatasRecord, 'newDatasRecord');

        //TODO,存储分页信息

        //存储该记录
        that.data.newDatasRecord = newDatasRecord;
        // 重新渲染页面
        that.setData({
          newsDatas: newDatasRecord.datas,
          hasNews: newDatasRecord.datas.length > 0
        });
      }
    });
  },
  toNewsItemDetail: function (e) {
    console.log("toNewsItemDetail", e);
    var id = e.detail.id;
    // 传递文章id
    wx.navigateTo({
      url: '../news_detail/index?id=' + id,
    })
  },
})